// gcc example2.c thpool.c -lpthread -D THREAD_DEBUG
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include "thpool.h"



const int S = 500000000;
int* arr;

typedef struct{
	int first;
	int last;
	int result;
}MY_ARGS;


void mysum(void *args){
	int i;
	int s=0;
	MY_ARGS* my_args = (MY_ARGS*) args;
	int first = my_args->first;
	int last = my_args->last;

	for(i=first;i<last;i++){
		s = s + arr[i];
	}
	my_args -> result = s;
//	return NULL;
//	printf("Thread #%u working on %d\n", (int)pthread_self(), (int*) arg);
}


int main(){
	
	int i;
	arr = malloc(sizeof(int) * S);

	for(i=0;i<S;i++){
		if(i%2==0)
			arr[i]=-i;
		else
			arr[i]=i;
	}

//	puts("Making threadpool with 4 threads");
	threadpool thpool = thpool_init(4);
	int task_num = 40;
//	puts("Adding 40 tasks to threadpool");
	int mid = S/task_num;

	MY_ARGS args[task_num];
	for (i=0; i<task_num-1; i++){
		args[i].first=i*mid;
		args[i].last=(i+1)*mid;
		args[i].result=0;
		thpool_add_work(thpool, mysum, &args[i]);
	};

	args[i].first =i*mid;
	args[i].last  =S;
	args[i].result=0;
	thpool_add_work(thpool, mysum, &args[i]);

	thpool_wait(thpool);
//	puts("Killing threadpool");
	thpool_destroy(thpool);

	int sum=0;
	for (i=0;i<task_num;i++){
		sum +=args[i].result;
	}
	printf("%d \n", sum);
	return 0;
}
